<?php
/**
 * 云门店
 */
defined('IN_IA') or exit('Access Denied');

class j_hmoneyModuleProcessor extends WeModuleProcessor {
	public function respond() {
		global $_W;
		$openid = $this->message['from'];
		$rid = $this->rule;
		$event=$this->message['event'];
		$cfg = $this->module['config'];
        if($cfg["debug"])$this->_sendText($openid,"开始渠道二维码回复调试");
		if($event=='SCAN' || $event=='subscribe'){
			$outTradeNo=$this->message['scene'];
			$reply=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_reply') . " WHERE weid = '{$_W['uniacid']}' and rid=:a",array(":a"=>$rid));
            if($cfg["debug"])$this->_sendText($openid,"start");
			if($reply['gtype']==2){
                if($cfg["debug"])$this->_sendText($openid,"收银小票二维码");
				$returnStr=$cfg["returnstr"];
                if(!$returnStr){
                    if($cfg["debug"])$this->_sendText($openid,"未设置系统回复模板");
                }
				/*小票*/
				load()->model('mc');
				$uid=mc_openid2uid($openid);
                if($cfg["debug"])$this->_sendText($openid,"是否存在会员-".$uid);
				if(!$uid)goto prize;
                $openinfo=mc_fetch($uid);
				$order=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '{$_W['uniacid']}' and id=:a",array(":a"=>$outTradeNo));
                if($cfg["debug"])$this->_sendText($openid,"判断订单状态");
				if($order['ispay']!=1 || !$order || $order['getmarketing'])goto end;
                if(intval($order['credit']*100))goto end;
				$shop=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_group') . " WHERE id =:a",array(":a"=>$order['groupid']));
                $shopid=$shop["id"];

				/*获得积分*/
				if(!intval($order['credit']*100)){
					$perCredit=$shop['creadit'] ? $shop['creadit'] : $cfg['credit'];
					$credit=sprintf('%.2f',($perCredit*$order['paid_fee']));
					if($credit){
						mc_credit_update($uid,"credit1",$credit,array("","收银台消费".$credit."扫码获得积分,单号：".$order['out_trade_no']));
						pdo_update("j_hmoney_order",array("credit"=>$credit),array("id"=>$order['id']));
					}
                    $openinfo=mc_fetch($uid);
				}

				prize:
				$openinfo=mc_fetch($uid);
				$returnStr=str_replace("|总积分|",$openinfo['credit1'] ? ($openinfo['credit1']+$credit) : 0,$returnStr);
				$returnStr=str_replace("|昵称|",$openinfo['nickname'],$returnStr);
				$returnStr=str_replace("|获得积分|",$credit ? $credit : 0,$returnStr);
                $fee=$order["paid_fee"];
				/*其他奖励*/

                if($cfg["debug"])$this->_sendText($openid,"判断奖励");
				if(!$order['marketing']){
					$marketlist=pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_marketing')." WHERE  weid = '{$_W['uniacid']}' and groupid=:a and fee*100<=:b and starttime<='".TIMESTAMP."' and endtime>='".TIMESTAMP."' and status=1  and ftype>1 order by displayorder asc",array(':a'=>$order['groupid'],":b"=>$order['paid_fee']));
					if(!$marketlist)goto success;
					$marketid=0;
					$marketItem=array();
					foreach($marketlist as $row){
						if(!$row['content'])continue;
						//会员等级判断
						if($row['memberlevel']){
							if(!$order['memberno'])continue;
							$mlevel=pdo_fetchcolumn("SELECT gid FROM ".tablename('j_hmoney_membercard')." WHERE id=:a ",array(":a"=>$order['memberno']));
							if(!in_array($mlevel,explode(',',$row['memberlevel'])))continue;
						}
						//星期判断
						if($row['limitweek']){
							$day=date('w') ? date('w') : 7;
							if(!in_array($day,explode(',',$row['limitweek'])))continue;
						}
						//时间段判断
						if($row['limithour']){
							$time=intval(date('h'));
							if(!in_array($time,explode(',',$row['limithour'])))continue;
						}
						$marketid=$row['id'];
						$marketItem=$row;
						break;
					}
					if(!$marketid)goto success;
					$content=$marketItem['content'];
					$returnAry=array(
						"mid"=>$marketid,
						"ftype"=>$marketItem['ftype'],
						"content"=>$marketItem['content'],
					);
					//返回优惠计算
					switch($marketItem['ftype']){
						//返卡券
						case 2:
							$temp=strpos($content,"|") ? explode("|",$content) : array($content);
							shuffle($temp);
							$cardkey=$temp[0];
							$returnStr=str_replace("|奖励|","卡券",$returnStr);
                            $results=$this->sendCard($openid,$cardkey);
                            if($cfg["debug"])$this->_sendText($openid,implode(",".$results));
						break;
						//返红包
						case 3:
                            if($cfg["debug"])$this->_sendText($openid,"奖励类型：红包");
							$couponfee=0;
                            $fee=$order['paid_fee'];
							if(strpos($content,"-")){
								$tempary=explode("-",$content);
								if(strpos($tempary[0],"%")){
									$couponfee=$fee*(mt_rand(str_replace("%","",$tempary[0]),str_replace("%","",$tempary[1]))*0.01);
								}else{
									$couponfee=mt_rand(intval($tempary[0]*100),intval($tempary[1]*100));
								}
							}else{
								if(strpos($content,"%")){
									$couponfee=$fee*(str_replace("%","",$content)*0.01);
								}else{
									$couponfee=$content*100;
								}
							}
                            if($cfg["debug"])$this->_sendText($openid,"红包金额：".$couponfee);
							if($couponfee>=100){
								$returnStr=str_replace("|奖励|","红包",$returnStr);
                                if($cfg["debug"])$this->_sendText($openid,"开始发放红包");
								$results=$this->_sendpack($openid,$shopid,$couponfee);
                                if($cfg["debug"])$this->_sendText($openid,implode(",".$results));
                                if($results["errno"]){
                                    pdo_update("j_hmoney_order",array("log"=>"红包发放错误：".$results["error"]),array("id"=>$order["id"]));
                                }
							}
						break;
						//返抽奖次数
						case 4:
							$coupon=0;
							$returnAry['gameid']=$marketItem['gameid'];
							if(strpos($content,"|")){
								$temp=explode("|",$content);
								$coupon=$fee % intval($temp[0]*100)*$temp[1];
							}else{
								$coupon=intval($content);
							}
							$insert=array(
								'weid'=>$_W['uniacid'],
								'gid'=>$returnAry['gameid'],
								'from_user'=>$openid,
							);
							for($i=0;$i<$coupon;$i++){
								pdo_insert("j_hmoney_lottery",$insert);
							}
							$returnStr=str_replace("|奖励|",'<a href="'.$_W['siteroot'].'app/index.php?i='.$_W['uniacid'].'&c=entry&id='.$returnAry['gameid'].'&do=game&m=j_hmoney">抽奖机会，点击进行抽奖</a>',$returnStr);
						break;
					}
				}
				success:
				$returnStr=str_replace("|奖励|","-",$returnStr);
				pdo_update("j_hmoney_order",array("getmarketing"=>1,"marketing"=>$marketid),array("id"=>$order['id']));
                if($cfg["debug"])$this->_sendText($openid,"最后判断奖励");
				if($returnStr)return $this->respText($returnStr);
				
			}elseif($reply['gtype']==1){
				/*兑换*/
                if($cfg["debug"])$this->_sendText($openid,"礼品兑换");
				$giftrecord=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_giftrecord')." WHERE id=:a ",array(':a'=>$outTradeNo));
				if($giftrecord['isget']){
					return $this->respText("礼品已被领取哦");
				}
				$shopid=$giftrecord["groupid"];
                switch($giftrecord['gtype']){
					case 1://卡券
						$this->sendCard($openid,$giftrecord['content']);
						pdo_update('j_hmoney_giftrecord',array('endtime'=>TIMESTAMP,'openid'=>$openid,'isget'=>1,'status'=>1),array('id'=>$giftrecord['id']));
					break;
					case 2://红包
						$result=$this->_sendpack($openid,$shopid,$giftrecord['content']);
                        pdo_update('j_hmoney_giftrecord',array('endtime'=>!$result['errno'] ? TIMESTAMP : 0,'openid'=>$openid,'isget'=>!$result['errno'] ? 1 : 0,'status'=>!$result['errno'] ? 1 : 0,'log'=>$result['error']),array('id'=>$giftrecord['id']));
					break;
				}
				
			}
		}
		end:
		return $this->respText("再次感谢您关注我们");
	}
	
	
	public function _sendText($openid,$txt){
		global $_W;
		$acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
		$acc = WeAccount::create($acid);
		$data = $acc->sendCustomNotice(array('touser'=>$openid,'msgtype'=>'text','text'=>array('content'=>urlencode($txt))));
		return $data;
	}
	/*
	* 卡券
	*/
	public function sendCard($openid,$cardid){
		global $_W;
		if(strlen($cardid)<5)return false;
		$acid=$_W['account']['acid'];
		if(!$acid){
			$acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
		}
		$acc = WeAccount::create($acid);
		$ticket=$this->getCard();
		$pars['nonce_str'] =$this->getNonceStr();
		$pars['code'] ="";
		$pars['openid'] =$openid;
		$pars['timestamp'] =TIMESTAMP;
		$pars['signature'] ="";
		//timestamp,nonce_str,code,ticket,card_id
        $string1=$pars['timestamp'].$pars['nonce_str'].$pars['code'].$ticket.$cardid;
		$pars['signature']=sha1($string1);
		$sendata=array(
			"card_id"=>$cardid,
			"card_ext"=>array(
				"code"=>$pars['code'],
				"openid"=>$pars['openid'],
				"timestamp"=>$pars['timestamp'],
				"signature"=>$pars['signature'],
			)
		);
		$data = $acc->sendCustomNotice(array('touser'=>$openid,'msgtype'=>'wxcard','wxcard'=>$sendata));
		return $data;
	}
	public function getCard(){
        global $_W;
		load()->func('cache');
		$wxcard=cache_load("wxcard");
		if(!$wxcard || $wxcard['extime']<TIMESTAMP){
			load()->func('communication');
			$acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
			$acc = WeAccount::create($acid);
			$tokens=$acc->fetch_token();
			$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$tokens."&type=wx_card";
			$content = ihttp_get($url);
			if(is_error($content))return false;
			$token = @json_decode($content['content'], true);
			if(empty($token) || !is_array($token)) {
				$errorinfo = substr($content['meta'], strpos($content['meta'], '{'));
				$errorinfo = @json_decode($errorinfo, true);
				return false;
			}
			$record = array();
			$record['ticket'] = $token['ticket'];
			$record['expire'] = TIMESTAMP + $token['expires_in'];
			cache_write("wxcard",array("ticket"=>$record['ticket'],"expire"=>$record['expire']));
			return $record['ticket'];
		}
		return $wxcard['ticket'];
	}
	public function getNonceStr($length = 32) {
		$chars = "abcdefghijklmnopqrstuvwxyz0123456789";  
		$str ="";
		for ( $i = 0; $i < $length; $i++ )  {  
			$str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);  
		} 
		return $str;
	}
	public function _sendpack($openid,$shopid,$fee){
		global $_W;
		$cfg = $this->module['config'];
		$shop=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_group')." WHERE id =:a",array(":a"=>$shopid));
 		$url='https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';
        $pars = array();
		$pars['nonce_str'] =$this->getNonceStr();
		$pars['mch_billno'] =$shop['pay_mchid'].date('YmdHis').mt_rand(1000, 9999);
		$pars['mch_id']=$shop['pay_mchid'] ? $shop['pay_mchid'] : $cfg['pay_mchid'];
		$pars['wxappid'] =$shop['appid'] ? $shop['appid'] : $cfg['appid'];
		$pars['send_name'] =$shop['companyname'];
		$pars['re_openid'] =$openid;
		$pars['total_amount'] =$fee;
		$pars['total_num'] =1;
		$pars['wishing'] ="礼品红包";
		$pars['client_ip'] =$cfg['mch_create_ip'];
		$pars['act_name'] =$shop['companyname'];
		$pars['remark'] =$shop['companyname'];
        ksort($pars, SORT_STRING);
        $string1='';
        foreach ($pars as $k => $v) {
            $string1 .= "{$k}={$v}&";
        }
        $pay_signkey=$shop['pay_signkey'] ? $shop['pay_signkey'] : $cfg['pay_signkey'];
        $string1 .= "key=".$pay_signkey;
        $pars['sign'] = strtoupper(md5($string1));
        $xml = array2xml($pars);
        $extras = array();
        $extras['CURLOPT_SSLCERT'] =IA_ROOT . '/attachment/j_hmoney/cert_2/'.$_W['uniacid']."/".$cfg['apiclient_cert'];
        $extras['CURLOPT_SSLKEY'] =IA_ROOT . '/attachment/j_hmoney/cert_2/'.$_W['uniacid']."/".$cfg['apiclient_key'];
		$procResult = null;
		load()->func('communication');
        $resp = ihttp_request($url, $xml, $extras);
        if (is_error($resp)) {
            $procResult = $resp;
        } else {
			$arr=json_decode(json_encode((array) simplexml_load_string($resp['content'])), true);
            $xml = '<?xml version="1.0" encoding="utf-8"?>' . $resp['content'];
            $dom = new \DOMDocument();
            if ($dom->loadXML($xml)){
                $xpath = new \DOMXPath($dom);
                $code = $xpath->evaluate('string(//xml/return_code)');
                $ret = $xpath->evaluate('string(//xml/result_code)');
                if (strtolower($code) == 'success' && strtolower($ret) == 'success') {
                    $procResult =  array('errno'=>0,'error'=>'success');
                } else {
                    $error = $xpath->evaluate('string(//xml/err_code_des)');
                    $procResult = array('errno'=>-2,'error'=>$error);
                }
            } else {
				$procResult = array('errno'=>-1,'error'=>'未知错误');				
            }
        }
		return $procResult;
	}
}